<template>
  <div class="typeadd">
    <el-container v-if="yc">
      <el-header>
        <div class="typeadd_header">
          <span>商品列表</span>
          <button @click="tj()">添加新的商品</button>
        </div>
      </el-header>
      <el-main>
        <el-table
          :data="list"
          border
          style="width: 100%"
          row-key="type"
          :lazy="true"
        >
          <el-table-column width="250" prop="name" label="名称">
          </el-table-column>
          <el-table-column width="100" prop="sn" label="编号">
          </el-table-column>
          <el-table-column width="100" prop="author" label="作者">
          </el-table-column>
          <el-table-column width="200" prop="publisher" label="出处">
          </el-table-column>
          <el-table-column width="200" prop="tpublish" label="日期">
          </el-table-column>
          <el-table-column prop="publisher" label="图片">
            <template #default="scope">
              <img
                :src="`${$Imgurl}/api/public/showImg/${
                  list[scope.$index].picture
                }`"
                style="width: 30%"
              />
            </template>
          </el-table-column>
          <el-table-column width="200" prop="tpublish" label="操作">
            <template #default="scope">
              <el-button
                type="warning"
                @click="
                  xg(
                    scope.row.id,
                    scope.row.name,
                    scope.row.sn,
                    scope.row.price,
                    scope.row.author,
                    scope.row.publisher,
                    scope.row.tpublish,
					scope.row.picture
                  )
                "
                >修改</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :page-size="num"
		  v-model:currentPage="pages"
        ></el-pagination>
      </el-main>
    </el-container>
    <!--  -->
    <el-container v-if="!yc">
      <el-header>
        <div class="typeadd_header">
          <span>{{ title }}</span>
        </div>
      </el-header>
      <el-main>
        <div>
          <el-form>
            <el-form-item label="商品名称">
              <el-input v-model.lazy="xgsp.name"></el-input>
            </el-form-item>
            <el-form-item label="商品序号">
              <el-input v-model.lazy="xgsp.sn"></el-input>
            </el-form-item>
            <el-form-item label="商品价格">
              <el-input v-model.lazy="xgsp.price"></el-input>
            </el-form-item>
            <el-form-item label="商品厂商">
              <el-input v-model.lazy="xgsp.author"></el-input>
            </el-form-item>
            <el-form-item label="商品出处">
              <el-input v-model.lazy="xgsp.publisher"></el-input>
            </el-form-item>
            <el-form-item label="出厂时间">
              <el-date-picker
                type="datetime"
                v-model="xgsp.tpublish"
                placeholder="选时间"
                @change="time"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="商品类型">
              <el-cascader
                :options="splxs"
                @change="handleChange"
                :show-all-levels="false"
              />
            </el-form-item>
            <el-form-item label="商品图片">
              <el-upload
                  class="avatar-uploader"
                  action=""
              	 :auto-upload="false"
              	list-type="picture-card"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
              	:http-request="upload"
              	 :limit='1'
              	  :on-remove="handleRemove"
              	   :on-change="handleChanges"
              	
                >
                  <img v-if="imageUrl" :src="`${$Imgurl}/api/public/showImg/${this.imageUrl}`" />
              
                 <aside>点击此处选择头像图片</aside> 
                </el-upload>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <button @click="ff()">返回列表</button>
          <button @click="upupdate()">提交</button>
        </div>
		<!--  -->
		<el-row class="ger_data1" style="margin: 0 auto; text-align: center;" >
			<el-container>
			<el-button  type="primary" style="margin: 0 auto;" @click='sumbits()'>提交</el-button>
			</el-container>
			
		</el-row>
      </el-main>
    </el-container>
  </div>
</template>

<script>
// 拦截器
import instance from "../../ajax/index.js";
import {mapState} from 'vuex'
import {mapMutations} from 'vuex'
import {
	ElMessage
} from 'element-plus'
// import { Plus } from "@element-plus/icons-vue";
export default {
  name: "Typeadd",
  data() {
    return {
      pages: 1,
      num: 5, //一页几条
      total: 40, //总条数+0
      title: "", //添加商品还是修改商品
      id: 0,
      //
      list: [],
      typeadd: [],
      a: 0,
      b: 1,
      xgsp: {
		id:'',
        name: "",
        sn: "",
        price: 0,
        author: "",
        publisher: "",
        tpublish: "",
        picture: "",
        type: "",
      },
      // 隐藏
      yc: true,
      // 二维数组
      splx: [],
      splxs: [],
      //另外
	  imageUrl: '',
	  file:'',
	  uploadform:{
		  docType: {
			crFile: []
		  }
	  },
	  uploadDisabled:false,
	  form: {
	  	username: '',
	  	password: '',
	  	grant_type: 'password', //获取token采用密钥模式
	  	client_id: 'sobook4', //应用ID
	  	client_secret: '444444' //秘钥
	  },
	  abc:'',
    };
  },
  watch: {
    pages() {
      this.btn();
    },
  },
  // 组件创建之后
  created() {
	this.btn();
    let that = this;
    // http://127.0.0.1:8093/api/adm/book/findByPage/1/5
    // // 发起get请求，获取数据
    instance.get("/api/adm/type/findAll2/").then((res) => {
        // 判断状态
        if (res.status === 200) {
          for (let index in res.data.data) {
            let obj = {
              id: res.data.data[index].id,
              value: res.data.data[index].type,
			  label:res.data.data[index].type,
              pid: res.data.data[index].pid,
              prio: res.data.data[index].prio,
              isdel: res.data.data[index].isdel,
            };
            that.splx.push(obj);
          }
		  // console.log(res.data.data);
          that.getMenu(0, that.splxs);
          console.log(that.splxs);
        }
      })
      .catch((error) => {
        console.log(error);
      });
	  console.log(this.xgsp);
    //
  },
  computed:{
  	...mapState(['img','pass']),
	
  },
  methods: {
	  ...mapMutations(['changepass']),
	  ...mapMutations(['changename']),
	  ...mapMutations(['changeid']),
    getMenu(id, arr) {
      // 判断
      if (id === 0) {
        // 第一级菜单
        this.splx.forEach((item) => {
          if (item.pid === 0) {
            arr.push(item);
          }
        });
        // 在第一级菜单完成之后，从第一级的第一个菜单开始，进入第二季菜单的筛选
        this.getMenu(this.splxs[0].id, this.splxs);
      } else {
        // 其他等级的菜单
        // 1.循环等级数组：给每个第一级找到第二级
        arr.forEach((item) => {
          // 2.将list整个循环，将每个第一级找到第二级
          this.splx.forEach((val) => {
            // 判断父级的id === 数据的pid【符合：数据是父级的子级菜单】
            if (item.id === val.pid) {
              // 声明一个下一维度的数组
              if (!item.children) item.children = [];
              // 将符合条件的数据，添加到child下
              item.children.push(val);
            }
          });
          // 每一个等级的36次循环结束之后，重新调用函数，进入下一个等级的操作
          if (item.child) {
            // 终止程序
            this.getMenu(1, item.children);
          }
        });
      }
    },
    // 点击的时间
    time(val) {
      // this.xgsp.tpublish = val.getTime();
	  this.xgsp.tpublish = this.zhuanhuan(val.getTime());
      console.log(new Date(this.xgsp.tpublish).getTime());
    },
    handleChange(val) {
		for(let index in this.splxs){
			for(let i in this.splxs[index].children){
				if(this.splxs[index].value==val[0]&&this.splxs[index].children[i].value==val[1]){
					console.log(this.splxs[index].children[i].id);
					this.xgsp.type = this.splxs[index].children[i].id;
				}
			}
		}
		
		
      // this.xgsp.type = val[val.length - 1];
	  
	  // console.log(val[1]);
    },
    // 提交
    tjs() {
      console.log(this.splxs);
    },
	// 添加
	tj(){
		this.yc = false;
	},
    btn() {
      instance.get("/api/adm/book/findByPage/" + this.pages + "/5").then((res) => {
          //
          // console.log(res.data.data.books);
          this.list = res.data.data.books;
		  this.total = res.data.data.total;
		  console.log(this.list);
        })
        .catch((error) => {
          console.log(error);
        });
    },
	// 返回
	ff(){
		this.yc = true;
	},
	// 修改
	xg(id,name,sn,price,author,publisher,tpublish,picture){
		this.imageUrl = picture;
		// console.log(s);
		this.yc = false;
		console.log(id,name,sn,price,author,publisher,tpublish);
		this.xgsp.id = id;
		this.xgsp.name = name;
		this.xgsp.sn = sn;
		this.xgsp.price = price;
		this.xgsp.author = author;
		this.xgsp.publisher = publisher;
		this.xgsp.tpublish = this.zhuanhuan(tpublish);
		// this.xgsp.tpublish = tpublish;
		
		console.log(tpublish);
	},
	passget(){
		console.log(this.abc);
	},
	sumbits(){
		console.log(this.xgsp);
		this.upload();
	},
	beforeAvatarUpload(file) {
	      const isimg = file.type === 'image/jpeg/'|| 'image/png/'|| 'image/gif/'||'image/webp/'
	      const isLt2M = file.size / 1024 / 1024 < 1.5
		  if (!isimg) {
			this.$message.error('图片格式不符')
			}
			if (!isLt2M) {
			this.$message.error('图片大于1.5MB')
			}
			return isimg && isLt2M
    },
	// 时间戳转换
	zhuanhuan(a){
		var now=new Date(a);
		var year=now.getFullYear();
		var month=now.getMonth()+1;
		var date=now.getDate();
		var hour=now.getHours();
		var minute=now.getMinutes();
		var second=now.getSeconds();
		return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
	},
	// 上传图片
	upload(){
		if(this.xgsp.id==''){
			const formData = new FormData();
			const fd = new FormData();
			  formData.append('id',0);
			  formData.append('name',this.xgsp.name);
			  formData.append('sn',this.xgsp.sn);
			  formData.append('author',this.xgsp.author);
			  formData.append('publisher',this.xgsp.publisher);
			  formData.append('tpublish',new Date(this.xgsp.tpublish).getTime());
			  formData.append('bookType.id',this.xgsp.type);
			  formData.append('pic',this.xgsp.picture.raw);
			  formData.append('price',this.xgsp.price);
			  // consol.log(this.file.raw.File);
			instance.post('/api/adm/book/addBook',formData,{ headers: {'Content-Type': 'multipart/form-data'}}).then((res)=>{
				console.log(res);
				// this.change
			  }).catch((error)=>{
				  console.log(error)
			  })
		}else{
			const formData = new FormData();
			const fd = new FormData();
			  formData.append('id',1);
			  formData.append('name',this.xgsp.name);
			  formData.append('sn',this.xgsp.sn);
			  formData.append('author',this.xgsp.author);
			  formData.append('publisher',this.xgsp.publisher);
			  formData.append('tpublish',new Date(this.xgsp.tpublish).getTime());
			  formData.append('bookType.id',this.xgsp.type);
			  formData.append('pic',this.xgsp.picture.raw);
			  formData.append('price',this.xgsp.price);
			  // consol.log(this.file.raw.File);
			instance.post('/api/adm/book/addBook',formData,{ headers: {'Content-Type': 'multipart/form-data'}}).then((res)=>{
				console.log(res);
				// this.change
			  }).catch((error)=>{
				  console.log(error)
			  })
		}
	},
	handleAvatarSuccess(res, file) {
	  this.imageUrl = URL.createObjectURL(file.raw)
	},
	handleRemove(file,fileList) {
	      //imgDelete.post({pic_name : file.response.pic_name}).then();
	  this.uploadDisabled = false;
	},
	handleChanges(file) {
		this.xgsp.picture = file;
	},
  }
};
</script>

<style scoped>
.typeadd_header {
  line-height: 80px;
}
.typeadd_header span {
  font-size: 20px;
  font-weight: bold;
}
.typeadd_header button {
  float: right;
  height: 23px;
  margin-top: 25px;
  margin-right: 25px;
  font-size: 10px;
}
.typeadd_bottom ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
.typeadd_bottom ul li:nth-child(1) p {
  height: 20px;
}
.typeadd_bottom ul li p {
  float: left;
  border: 1px solid black;
  width: 13.5%;
  height: 100px;
}
.typeadd_bottom ul li img {
  width: 100%;
}
.oll {
  border: 1px solid black;
  line-height: 50px;
  float: left;
}
.oll li:nth-child(1) {
  width: 70px;
}
.oll li {
  float: left;
  text-align: center;
  width: 30px;
  height: 30px !important;
  line-height: 30px;
  border: 1px solid black;
}
.abc {
  background-color: #0000e8;
  color: white;
}
</style>
